<?php

namespace addons\wechatlogin\controller;

use addons\third\library\Application;
use addons\third\library\Service;
use think\addons\Controller;
use think\Cookie;
use think\Hook;
use think\Session;

/**
 * 第三方登录插件
 */
class Third extends Controller
{
    protected $app = null;
    protected $options = [];

    public function _initialize()
    {
        parent::_initialize();
        $config = get_addon_config('third');
        if (!$config) {
            $this->error(__('Invalid parameters'));
        }
        $options = array_intersect_key($config, array_flip(['qq', 'weibo', 'wechat']));
        foreach ($options as $k => &$v) {
            $v['callback'] = addon_url('wechatlogin/third/callback', [':platform' => $k], false, true);
            $options[$k] = $v;
        }
        unset($v);
        $this->app = new Application($options);
    }

    /**
     * 发起授权
     */
    public function connect()
    {
        $platform = 'wechat';
        $url = $this->request->request('url', '', 'trim');
        if (!$this->app->{$platform}) {
            $this->error(__('Invalid parameters'));
        }
        $config = get_addon_config('wechatlogin');
        $password = $config['password'];
        $pw = $this->request->request('pw', '');
        if ($pw != $password) {
            $this->error('通信密码错误');
        }

        if ($url) {
            Session::set("redirecturl", base64_decode($url));
        }

        // 跳转到登录授权页面
        $this->redirect($this->app->{$platform}->getAuthorizeUrl());
        return;
    }

    /**
     * 通知回调
     */
    public function callback()
    {
        $platform = 'wechat';

        // 成功后返回之前页面
        $url = Session::has("redirecturl") ? Session::pull("redirecturl") : url('third/index/callback');

        // 授权成功后的回调 [主服务器使用]
        $result = $this->app->{$platform}->getUserInfo();
        if ($result) {
            $config = get_addon_config('wechatlogin');
            $result['pw'] = $config['password'];
            $url .= "?data=" . base64_encode(json_encode($result));

            $this->redirect($url);
            return;
        }
        $this->error(__('操作失败'), $url);
    }

    /**
     * 通知回调
     */
    public function callback_client()
    {
        $auth = $this->auth;
        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });

        $platform = 'wechat';

        //成功后返回之前页面 [从服务器使用]
        $url = Session::has("redirecturl_client") ? Session::pull("redirecturl_client") : url('index/user/index');

        $result = json_decode(base64_decode($this->request->param('data')), true);
        $config = get_addon_config('wechatlogin');
        if ($result['pw'] != $config['password']) {
            $this->error(__('通信密码错误'), $url);
        }

        if ($result) {
            $loginret = Service::connect($platform, $result);
            if ($loginret) {
                $this->redirect($url);
                //$this->success(__('登录成功'), $url);
            }
        }
        $this->error(__('操作失败'), $url);
    }
}
